//
//  MineViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/6/3.
//

import UIKit
struct CellDataSource {
    var tag: String
    var title: String
    var imageName: String = ""
    var desc:String?
    var cellType: UITableViewCell.Type
}
class MineViewController: BaseViewController {
    let disposeBag = DisposeBag()
    let viewModel = LoginViewModel()
    lazy var headView: MineHeaderView = {
       let view = MineHeaderView()
        view.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: GET_WIDTH(W: 288))
        return view
    }()
    
    var dataSource: [CellDataSource] = {
        
        let user = CellDataSource(tag: "user", title: "用户信息", imageName: "icon_Mine_用户信息", cellType: MineItemTableViewCell.self)
        let works = CellDataSource(tag: "works", title: "我的作品", imageName: "icon_Mine_works", cellType: MineItemTableViewCell.self)
        let collect = CellDataSource(tag: "collect", title: "收藏", imageName: "icon_Mine_收藏", cellType: MineItemTableViewCell.self)
        let xy = CellDataSource(tag: "xy", title: "隐私协议", imageName: "icon_Mine_协议", cellType: MineItemTableViewCell.self)
        let tk = CellDataSource(tag: "tk", title: "使用条款", imageName: "icon_Mine_条款", cellType: MineItemTableViewCell.self)
        let lx = CellDataSource(tag: "lx", title: "联系我们", imageName: "icon_Mine_联系", cellType: MineItemTableViewCell.self)
        let mail = CellDataSource(tag: "mail", title: "客服邮箱", imageName: "icon_mine_mail", desc: "service@letonglive.com", cellType: MineItemTableViewCell.self)
        let gy = CellDataSource(tag: "gy", title: "关于我们", imageName: "icon_Mine_关于", cellType: MineItemTableViewCell.self)
         return [user, works, collect, xy, tk ,lx, mail, gy]
     }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        viewModel.getUserInfo()
        self.headView.setup()
        self.tableView.reloadData()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(cellWithClass: MineEquityTableViewCell.self)
        tableView.register(cellWithClass: MineItemTableViewCell.self)
        tableView.register(cellWithClass: MineDiamondCell.self)
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.contentInsetAdjustmentBehavior = .never
        
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hexString: "#F3F2F7")
//        self.view.addSubview(self.headView)
        self.view.addSubview(tableView)
//        self.headView.snp.makeConstraints { make in
//            make.top.leading.trailing.equalToSuperview()
//            make.height.equalTo(GET_WIDTH(W: 288))
//        }
        self.tableView.snp.makeConstraints { make in
//            make.top.equalTo(self.headView.snp.bottom)
            make.top.equalToSuperview()
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(self.safeBottom)
        } 
        
        self.tableView.tableHeaderView = self.headView
        
        GlobalRx.userInfoSubject.observe(on: MainScheduler.instance).subscribe(onNext: { model in
            self.headView.setup()
            self.tableView.reloadData()
        }).disposed(by: disposeBag)
    }
    
}
extension MineViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 || section == 1 {
            return 1
        }else {
            return self.dataSource.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withClass: MineEquityTableViewCell.self, for: indexPath)
            if let vip = Appearance.shared.accoutModel?.userOtherInfo?.is_vip, vip == 1 {
                if Appearance.shared.accoutModel?.userOtherInfo?.vip_end_time?.checkVIPExpiryDate() == false
                {
                    cell.subBtn.isHidden = true
                }else {
                    cell.subBtn.titleForNormal = "立即续费"
                    cell.subBtn.isHidden = false
                }
            }else {
                cell.subBtn.isHidden = false
            }
            return cell
        }else if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withClass: MineDiamondCell.self, for: indexPath)
            cell.moneyLb.text = "\(Appearance.shared.accoutModel?.userOtherInfo?.score ?? 0)"
             return cell
        } else {
            let data = self.dataSource[indexPath.item]
            let cell = tableView.dequeueReusableCell(withClass: MineItemTableViewCell.self, for: indexPath)
            cell.iconIV.image = UIImage(named: data.imageName)
            cell.titleLb.text = data.title
            cell.descLb.text = data.desc
             return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            if !Appearance.shared.isLoign {
                GlobalRx.loginSubject.onNext(())
                return
            }
            let vc = DiamondBuyViewController()
            self.navigationController?.pushViewController(vc)
        }
        else if indexPath.section == 2 {
            let data = self.dataSource[indexPath.item]
            if data.tag == "user" {
                if Appearance.shared.isLoign {
                    self.navigationController?.pushViewController(UserInfoViewController())
                }else {
                    GlobalRx.loginSubject.onNext(())
                }
                return
            }
            if data.tag == "works" {
                if Appearance.shared.isLoign {
                    self.navigationController?.pushViewController(WorksPageViewController())
                }else {
                    GlobalRx.loginSubject.onNext(())
                }
                return
            }
            if data.tag == "xy" {
                if let url = URL(string: "\(apiHost)/api/text/privacy") {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
                return
            }
            if data.tag == "tk" {
                if let url = URL(string: "\(apiHost)/api/text/contract") {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
                return
            }
            if data.tag == "mail" {
                let email = "service@letonglive.com"
                if let emailUrl = URL(string: "mailto:\(email)") {
                    if UIApplication.shared.canOpenURL(emailUrl) {
                        UIApplication.shared.open(emailUrl, options: [:], completionHandler: nil)
                    }
                }
                return
            }
            data.tag == "gy" ? self.navigationController?.pushViewController(AboutViewController()) : nil
            data.tag == "lx" ? self.navigationController?.pushViewController(FeedbookViewController()) : nil
            data.tag == "collect" ? self.navigationController?.pushViewController(CollectViewController()) : nil
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if let vip = Appearance.shared.accoutModel?.userOtherInfo?.is_vip, vip == 1, 
                Appearance.shared.accoutModel?.userOtherInfo?.vip_end_time?.checkVIPExpiryDate() == false {
                return 124
            }else {
                return 180
            }
        } else if indexPath.section == 1{
            return UITableView.automaticDimension
        }else {
            return 56
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        section == 2 ? 14 : 0.01
    }
    
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.section == 2 {
            let radius = 8.0
            cell.backgroundColor = UIColor.clear
            let normalLayer = createLayer(with: radius, bounds: cell.bounds.insetBy(dx: 14.0, dy:0), tableView: tableView, indexPath: indexPath)
            let selectLayer = createLayer(with: radius, bounds: cell.bounds.insetBy(dx: 14.0, dy:0), tableView: tableView, indexPath: indexPath)
            cell.backgroundView = createBackgroundView(with: normalLayer, bounds: cell.bounds.insetBy(dx: 14.0, dy:0))
            cell.selectedBackgroundView = createBackgroundView(with: selectLayer, bounds: cell.bounds.insetBy(dx: 14.0, dy:0))
        }
    }

    func createLayer(with radius: Double, bounds: CGRect, tableView: UITableView, indexPath: IndexPath) -> CAShapeLayer {
        let layer = CAShapeLayer()
        layer.path = createBezierPath(with: radius, bounds: bounds, tableView: tableView, indexPath: indexPath).cgPath
        layer.fillColor = UIColor(hexString: "#FFFFFF").cgColor
        return layer
    }

    func createBezierPath(with radius: Double, bounds: CGRect, tableView: UITableView, indexPath: IndexPath) -> UIBezierPath {
        let rowNum = tableView.numberOfRows(inSection: indexPath.section)
        if rowNum == 1 {
            return UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii:CGSize(width: radius, height: radius))
        } else if indexPath.row == 0 {
            return UIBezierPath(roundedRect: bounds, byRoundingCorners: [UIRectCorner.topLeft,UIRectCorner.topRight], cornerRadii:CGSize(width: radius, height: radius))
        } else if indexPath.row == rowNum-1 {
            return UIBezierPath(roundedRect: bounds, byRoundingCorners: [UIRectCorner.bottomLeft,UIRectCorner.bottomRight], cornerRadii:CGSize(width: radius, height: radius))
        } else {
            return UIBezierPath(rect: bounds)
        }
    }

    func createBackgroundView(with layer: CAShapeLayer, bounds: CGRect) -> UIView {
        let bgView = UIView(frame: bounds)
        bgView.layer.insertSublayer(layer, at:0)
        bgView.backgroundColor = UIColor.clear
        return bgView
    }
}

class MineHeaderView: UIView {
    private lazy var headerImage: UIImageView = {
       let imageView = UIImageView()
        imageView.image = UIImage(named: "icon_mine_header")
        imageView.contentMode = .scaleToFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    private lazy var lockView: UIView = {
       let view = UIView()
        view.backgroundColor = UIColor(hexString: "#25262B")
        view.corners([.layerMinXMinYCorner, .layerMaxXMinYCorner], cornerRadius: 8)
        return view
    }()
    
    private lazy var lockImg: UIImageView = {
       let imageView = UIImageView()
        imageView.image = UIImage(named: "icon_mine_解锁更多权益")
        imageView.contentMode = .scaleToFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    private lazy var lockLb: UILabel = {
       let label = UILabel()
        label.text = "解锁更多权益"
        label.textColor = .white
        label.font = UIFont.pingFangSCMedium(ofSize: 15)
        return label
    }()
    
    private lazy var vipLb: UILabel = {
       let label = UILabel()
        label.text = ""
        label.textColor = UIColor(hexString: "#FFB056")
        label.font = UIFont.pingFangSCMedium(ofSize: 12)
        label.isHidden = true
        return label
    }()
    
    private lazy var moreIV: UIImageView = {
       let imageView = UIImageView()
        imageView.image = UIImage(named: "icon_Mine_更多权益")
        imageView.contentMode = .scaleToFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        self.addSubview(headerImage)
        self.addSubview(lockView)
        lockView.addSubviews([lockImg, lockLb, vipLb, moreIV])
        
        headerImage.snp.makeConstraints { make in
            make.top.trailing.equalToSuperview()
            make.leading.equalToSuperview().offset(-1)
            make.height.equalTo(GET_WIDTH(W: 288))
        }
        
        lockView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.leading.trailing.equalToSuperview().inset(14)
            make.height.equalTo(50)
        }
        
        lockImg.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.equalToSuperview().offset(15)
            make.width.equalTo(26)
            make.height.equalTo(23)
        }
        
        lockLb.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(lockImg.snp.trailing).offset(8)
        }
        
        moreIV.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-15)
        }
        setup()
        
        
        
        self.setOneTappedWithCallback_k { [weak self] in
            self?.sub()
        }
    }
    
    func sub(){
        if Appearance.shared.accoutModel != nil {
            let vc = SubscribeViewController()
            self.parentViewController?.navigationController?.pushViewController(vc, animated: true)
        }else {
            GlobalRx.loginSubject.onNext(())
        }
    }
    
    func setup() {
        let user = Appearance.shared.accoutModel?.userOtherInfo
        if let isVip = user?.is_vip, isVip == 1 {
            lockLb.text = "你的AI会员"
            lockView.snp.remakeConstraints { make in
                make.bottom.equalToSuperview()
                make.leading.trailing.equalToSuperview().inset(14)
                make.height.equalTo(60)
            }
            lockLb.snp.remakeConstraints { make in
                make.centerY.equalToSuperview().offset(-7)
                make.leading.equalTo(lockImg.snp.trailing).offset(8)
            }
            vipLb.snp.remakeConstraints { make in
                make.top.equalTo(lockLb.snp.bottom).offset(0)
                make.leading.equalTo(lockImg.snp.trailing).offset(8)
            }
            vipLb.isHidden = false
        }else {
            lockLb.text = "解锁更多权益"
            vipLb.isHidden = true
            lockView.snp.remakeConstraints { make in
                make.bottom.equalToSuperview()
                make.leading.trailing.equalToSuperview().inset(14)
                make.height.equalTo(50)
            }
              
            lockLb.snp.remakeConstraints { make in
                make.centerY.equalToSuperview()
                make.leading.equalTo(lockImg.snp.trailing).offset(8)
            }
        }
        
        if let vip_end_time = user?.vip_end_time {
            if vip_end_time.checkVIPExpiryDate() == false {
                vipLb.text = "终身会员"
            }else {
                vipLb.text = "到期时间: \(vip_end_time.vipExpirationTime() ?? "")"
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
}
